#!/usr/bin/python

import pydelicious 
from bookmarks.models import Bookmark
from django.contrib.auth.models import User
from django.db.models import force_unicode

# open our file

def import_delicious(filename, username):
  '''
    Rough import utility to import a del.icio.us xml file to a Django model.

    XML file generated from https://api.del.icio.us/v1/posts/all?user=USERNAME

    Note: pydelicious depends on feedparser, and Django, of course, depends on django
  '''

  fileobj = open(filename, 'r')

  # parse out del.icio.us xml entries into python
  # dictionaries 

  parsed = pydelicious.dlcs_parse_xml(fileobj) 

  # choose which user we want to export these to

  owner = User.objects.get(username__exact='%s' % username)

  # iterate through the dictionary, and save the posts to our Bookmark model

  for post in parsed['posts']:
    bookmark = Bookmark(title = force_unicode(post['description']),
                        description = force_unicode(post['extended']),
                        tags = force_unicode(post['tag']),
                        url = force_unicode(post['href']),
                        created_date = force_unicode(post['time']),
                        modified_date = force_unicode(post['time']),
                        user = owner)
    try:
      bookmark.save()
    except: 
      print '''import of "%s" failed\nURL: %s\nTAGS: %s ''' % (post['description'], post['href'], post['tag'])


if __name__ == 'main':

  import_delicious('/home/username/delicious_username.xml', 'username')
